//
//  PPPetCircleTableViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 8/4/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPPetCircleTableViewController.h"
#import "PPCircleMsgTableViewController.h"
#import "PPSelectTagViewController.h"
#import "supportingHeadFiles.h"
#import "PPCustomBGTableView.h"
#import "PPPetCircleTableViewCell.h"
#import "PPComment.h"
#import "PPTopic.h"
#import "PPUserInfo.h"
#import "PPCirclePush.h"

#import "PPUserCenterMainPageTableViewController.h"
#import "PPOtherUserCardViewController.h"
#import "PPImageDisplayViewController.h"
#import "PPTopicDetailViewController.h"

#import "PPSystemConfiguraton.h"
#import "EGORefreshTableFooterView.h"

typedef enum LOADTYPE
{
    UP = 0,
    DWON,
}LOADTYPE;


@interface PPPetCircleTableViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,EGORefreshTableFooterDelegate,UIActionSheetDelegate>{
    EGORefreshTableFooterView *refreshView;
    BOOL _reloading;
}

@property (weak, nonatomic) PPSystemConfiguraton *config;

@property (weak, nonatomic) IBOutlet PPCustomBGTableView *myTableView;
@property (nonatomic, strong) NSMutableArray *topicArray; // topicArray
//commentView
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet UITextField *addCommentTF;
@property (nonatomic) BOOL canReturn; //keyBoard 是否可以缩回
@property (nonatomic) int choseRow; // 选择回复的哪一行
@property (nonatomic, strong) UIRefreshControl *refreshControl; //下拉刷新
@property (nonatomic) int targetId;
@property (nonatomic) int lastId;
@property (nonatomic) BOOL canLoadMore;
@property (nonatomic) LOADTYPE type;
@property (nonatomic) int deleteReplyId;
@property (nonatomic) int changeTopicRow;

@property (nonatomic) float keyboardHeight;
@property (weak, nonatomic) IBOutlet UIView *tableHeadView;
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@end

@implementation PPPetCircleTableViewController
- (NSMutableArray *)topicArray
{
    if (!_topicArray) {
        _topicArray = [NSMutableArray array];
    }
    return _topicArray;
}

-(PPSystemConfiguraton *)config{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.myTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.myTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.myTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.myTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.targetId = 0;
    self.type = DWON;
    self.lastId = 0;
    refreshView = [[EGORefreshTableFooterView alloc]initWithFrame:CGRectMake(0, 1, 250, 44) andCheck:YES];
    refreshView.delegate = self;
    self.myTableView.tableFooterView = refreshView;
    self.canLoadMore = YES;
    _reloading = NO;
    //下拉刷新控件
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    [self.myTableView addSubview:self.refreshControl];
    
    self.canReturn = NO;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.commentView.hidden = YES;
    self.addCommentTF.delegate = self;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];
    
    [HUD showUIBlockingIndicatorWithText:@"正在加载"];
    [self dataInit];
    //gesture
    UITapGestureRecognizer *viewRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goMsgList)];
    self.contentView.userInteractionEnabled = YES;
    viewRecognizer.numberOfTouchesRequired = 1;
    viewRecognizer.numberOfTapsRequired = 1;
    [self.contentView addGestureRecognizer:viewRecognizer];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (self.config.circleArray.count > 0) {
        [self getHeadView];
        self.tableHeadView.hidden = NO;
        CGRect frame = self.tableHeadView.frame;
        frame.size.height = 44;
        self.tableHeadView.frame = frame;
    }else{
        self.tableHeadView.hidden = YES;
        CGRect frame = self.tableHeadView.frame;
        frame.size.height = 0;
        self.tableHeadView.frame = frame;
    }
    self.myTableView.tableHeaderView = self.tableHeadView;
    [self.myTableView reloadData];
}

- (void)getHeadView
{
    PPCirclePush *circlePush = self.config.circleArray.firstObject;
    [self.avatar setImageWithURL:[PPImageUrl getImageUrl:circlePush.pubUser.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.countLabel.text = [NSString stringWithFormat:@"%@条新消息",@(self.config.circleArray.count)];
}

- (void)goMsgList
{
    PPCircleMsgTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPCircleMsgTableViewController"];
    [self.navigationController pushViewController:targetVC animated:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)refreshTableView{
    
    self.type = DWON;
    self.canLoadMore = YES;
    refreshView.hidden = NO;
    
    [self dataInit];
}


-(void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView *)view
{
    if (self.canLoadMore) {
        self.type = UP;
        [self dataInit];
    }
}
//返回当前刷新状态:是否在刷新
-(BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView *)view
{
    return _reloading;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(self.canLoadMore)
    {
        [refreshView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}



#pragma mark - notification
-(void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary* userInfo = [notification userInfo];
    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: 0.3f];
    // get the size of the keyboard
    CGSize keyboardSizeE = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    // resize tableview
    self.keyboardHeight = keyboardSizeE.height;
    CGSize keyboardSize = keyboardSizeE;
    CGRect tableframe = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)  ;
    tableframe.size.height = tableframe.size.height - keyboardSize.height - 44;
    self.myTableView.frame = tableframe;
    CGRect commentframe = CGRectMake(0, self.view.frame.size.height - 44, 320, 44);
    commentframe.origin.y -= keyboardSize.height;
    self.commentView.frame = commentframe;
    [UIView commitAnimations];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    if (self.canReturn) {
        NSDictionary* userInfo = [notification userInfo];
        [UIView beginAnimations: @"animateTextField" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: 0.2f];
        // get the size of the keyboard
        CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
        // resize tableview
        CGRect frame = self.myTableView.frame;
        frame.size.height += keyboardSize.height + 44;
        self.myTableView.frame = frame;
        // set footer's frame
        frame = self.commentView.frame;
        frame.origin.y += keyboardSize.height;
        self.commentView.frame = frame;
        [UIView commitAnimations];
    }
}

-(void)keyboardDidShow:(NSNotification *)notification
{
    self.canReturn = YES;
}

-(void)keyboardDidHide:(NSNotification *)notification
{
    self.canReturn = NO;
}


-(void)dataInit
{
    if (self.type == DWON) {
        self.lastId = 1;
    }else {
        self.lastId ++;
        _reloading =YES;
    }
    NSString *url = [PPAPIList getAPIList].PPQueryLatestTopicByTargetId;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"pageSize":@10, @"pageIndex":@(self.lastId)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"new topic json is %@",responseObject);
        
        if (self.type == DWON) {
            [self.topicArray removeAllObjects];
        }
//        int totalCount = 0;
        NSDictionary *resultMap = responseObject[@"resultMap"];
        NSNumber *totalNum = resultMap[@"totalCount"];
        int totalCount = totalNum.intValue;
        NSArray *list = resultMap[@"list"];
        for (NSDictionary *topicDic in list) {
            NSError *err = nil;
            PPTopic *topic = [[PPTopic alloc] initWithDictionary:topicDic error:&err];
            [self.topicArray addObject:topic];
        }
        if (self.topicArray.count >= totalCount) {
            self.canLoadMore = NO;
            refreshView.hidden = YES;
        }
        [self.myTableView reloadData];
        if (self.type == DWON) {
            [self.refreshControl endRefreshing];
        }else {
            [refreshView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
            _reloading = NO;
            
        }
        [HUD hideUIBlockingIndicator];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"new topic json is %@",error);
    }];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat topicHeight = [self heightForTopicContentAtIndexPath:indexPath];
    CGFloat imageHeight = [self heightForImageDisplayViewAtIndexPath:indexPath];
    CGFloat conmentHeight = [self heightForconmentViewAtIndexPath:indexPath];
    CGFloat height = 34 + topicHeight + 10 + imageHeight + 38 + conmentHeight + 15;
    return height > 108 ? height:108;
}

- (CGFloat)heightForTopicContentAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetCircleTableViewCell *cell = (PPPetCircleTableViewCell *)[self tableView:self.myTableView cellForRowAtIndexPath:indexPath];
    if (cell.topicCotnentLabel.text) {
        CGFloat Height =cell.topicCotnentLabel.frame.size.height;
        return Height;
    }
    return 0;
}

- (CGFloat)heightForImageDisplayViewAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetCircleTableViewCell *cell = (PPPetCircleTableViewCell *)[self tableView:self.myTableView cellForRowAtIndexPath:indexPath];
    if (cell.topicCotnentLabel.text) {
        CGFloat Height =cell.pictureDisplayView.frame.size.height;
        return Height;
    }
    return 0;
}

- (CGFloat)heightForconmentViewAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetCircleTableViewCell *cell = (PPPetCircleTableViewCell *)[self tableView:self.myTableView cellForRowAtIndexPath:indexPath];
    if (cell.topicCotnentLabel.text) {
        CGFloat Height =cell.commentView.frame.size.height;
        return Height;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetCircleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pcCell"];
    PPTopic *topic = [self.topicArray objectAtIndex:indexPath.row];
    for (PPLabel *subView in cell.commentView.subviews)
    {
        [subView removeFromSuperview];
    }
    for (UIImageView *subView in cell.pictureDisplayView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    PPUserInfo *user = topic.userList.firstObject;
    //image
    [cell.userAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    if (user.gender == USER_MALE) {
        [cell.userGenderImageView setImage:[UIImage imageNamed:@"uc_male"]];
    }else{
        [cell.userGenderImageView setImage:[UIImage imageNamed:@"uc_female"]];
    }
    //label
    cell.userNameLabel.text = user.userName;
    cell.topicCotnentLabel.text = topic.content;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:topic.publicDate];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    
    cell.publicDateLabel.text = [formatter stringFromDate:date];
    //button
    [cell.userCenterButton addTarget:self action:@selector(pushToUserCenter:) forControlEvents:UIControlEventTouchUpInside];
    cell.userCenterButton.tag = indexPath.row;
    [cell.rockButton addTarget:self action:@selector(pressRock:) forControlEvents:UIControlEventTouchUpInside];
    cell.rockButton.tag = indexPath.row;
    [cell.commentButton addTarget:self action:@selector(pressComment:) forControlEvents:UIControlEventTouchUpInside];
    cell.commentButton.tag = indexPath.row;
    
    [cell.rockButton setTitle:[NSString stringWithFormat:@"  %@",@(topic.topicLikeNum.count)] forState:UIControlStateNormal];
    [cell.commentButton setTitle:[NSString stringWithFormat:@"  %@",@(topic.replyNum.count)] forState:UIControlStateNormal];
    //special
    
    
    
    cell.pictureDisplayView = [PPImageShowViewNine setImageWithImage:topic.topicImgList andView:cell.pictureDisplayView];
    cell.commentView = [PPcommentDisplayView setViewWithComment:topic.replyNum andView:cell.commentView];
    //set pos
    [cell.userNameLabel sizeToFit];
    cell.userGenderImageView.frame = CGRectMake(60 + cell.userNameLabel.frame.size.width + 5, 15, 12, 12);
    
    cell.topicCotnentLabel.frame = CGRectMake(60, 34, 240, 14);
    cell.topicCotnentLabel.numberOfLines = 0;
    cell.topicCotnentLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [cell.topicCotnentLabel sizeToFit];
    cell.topicCotnentLabel.frame = CGRectMake(60, 34, cell.topicCotnentLabel.frame.size.width, cell.topicCotnentLabel.frame.size.height);
    
    CGFloat imageVY = 34 + cell.topicCotnentLabel.frame.size.height + 10;
    cell.pictureDisplayView.frame = CGRectMake(60, imageVY, 240, [PPImageShowViewNine getViewHeight:topic.topicImgList]);
    
    cell.rockButton.frame = CGRectMake(174, cell.pictureDisplayView.frame.size.height + imageVY + 8, 58, 27);
    cell.commentButton.frame = CGRectMake(240, cell.pictureDisplayView.frame.size.height + imageVY + 8, 58, 27);
    
    cell.publicDateLabel.frame = CGRectMake(60, cell.pictureDisplayView.frame.size.height + imageVY + 16, 106, 11);
    
    CGFloat commentVY = imageVY + cell.pictureDisplayView.frame.size.height + 38;
    cell.commentView.frame = CGRectMake(60, commentVY, 240, [PPcommentDisplayView getViewHeigt:topic.replyNum]);
 
    //add gesture
    int i = 0;
    for (PPLabel *subView in cell.commentView.subviews)
    {
        subView.userInteractionEnabled = YES;
        subView.tag = i;
        subView.row = indexPath.row;
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(replys:)];
        recognizer.numberOfTouchesRequired = 1;
        recognizer.numberOfTapsRequired = 1;
        [subView addGestureRecognizer:recognizer];
        i++;
    }
    for (UIImageView *subView in cell.pictureDisplayView.subviews)
    {
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scaleImages:)];
        subView.userInteractionEnabled = YES;
        recognizer.numberOfTouchesRequired = 1;
        recognizer.numberOfTapsRequired = 1;
        subView.tag = indexPath.row;
        [subView addGestureRecognizer:recognizer];
        i++;
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPTopicDetailViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPTopicDetailViewController"];
    targetVC.topic = [self.topicArray objectAtIndex:indexPath.row];
    [self.addCommentTF resignFirstResponder];
    self.commentView.hidden = YES;
    [self.navigationController pushViewController:targetVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(CGFloat) getBeforCellHeight:(int)row
{
    CGFloat height = 0;
    for (int i = 0; i < row; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        CGFloat topicHeight = [self heightForTopicContentAtIndexPath:indexPath];
        CGFloat imageHeight = [self heightForImageDisplayViewAtIndexPath:indexPath];
        CGFloat conmentHeight = [self heightForconmentViewAtIndexPath:indexPath];
        CGFloat cellHeight = 34 + topicHeight + 10 + imageHeight + 38 + conmentHeight + 15;
        if (cellHeight < 108) {
            cellHeight = 108;
        }
        height += cellHeight;
    }
    return height;
}

#pragma mark - Action

-(void)actionSheetShow
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"删除", nil];
    [choiceSheet showInView:self.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        return;
    }else if (buttonIndex == 0){
        [self deleteReply];
    }
}

-(void)deleteReply
{
    NSString *url = [PPAPIList getAPIList].PPDeleteReplyComment;
    NSDictionary *params = @{@"replyId":@(self.deleteReplyId)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"delete response is %@",responseObject);
        PPTopic *topic = [self.topicArray objectAtIndex:self.changeTopicRow];
        NSString *queryUrl = [PPAPIList getAPIList].PPQueryTopicById;
        NSDictionary *queryParams = @{@"topicId":@(topic.id)};
        [httpRequst POST:queryUrl parameters:queryParams success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"topic Json is %@",responseObject);
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicArray = resultMap[@"topic"];
            NSError *err = nil;
            PPTopic *replaceTopic = [[PPTopic alloc] initWithDictionary:topicArray.firstObject error:&err];
            [self.topicArray replaceObjectAtIndex:self.changeTopicRow withObject:replaceTopic];
            [self.myTableView reloadData];
        }failure:^(AFHTTPRequestOperation *operation , NSError *error){
            
        }];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)replys:(UITapGestureRecognizer *)sender
{
    UITapGestureRecognizer *tap = sender;
    PPLabel *label= (PPLabel *)tap.view;
    NSLog(@"label%d",label.tag);
    PPTopic *nowTopic = [self.topicArray objectAtIndex:label.row];
    PPComment *nowComment = [nowTopic.replyNum objectAtIndex:label.tag];
    if (nowComment.userId == self.config.userInfo.id) {
        NSLog(@"delete");
        self.deleteReplyId = nowComment.id;
        self.changeTopicRow = label.row;
        [self actionSheetShow];
    }else{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:label.row inSection:0];
        [self.myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        PPPetCircleTableViewCell *cell = (PPPetCircleTableViewCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
        self.commentView.hidden = NO;
        [self.addCommentTF becomeFirstResponder];
        CGPoint point = CGPointMake(0, cell.frame.size.height + self.keyboardHeight + 44 - self.view.frame.size.height + [self getBeforCellHeight:label.row]);
        [self.myTableView setContentOffset:point animated:YES];
        self.addCommentTF.tag = label.row;
        self.targetId = nowComment.userId;
    }
}

- (void)scaleImages:(UITapGestureRecognizer *)sender
{
    NSLog(@"click");
    UITapGestureRecognizer *tap = sender;
    UIImageView *image= (UIImageView *)tap.view;
    NSLog(@"image %d",image.tag);

    PPImageDisplayViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPImageDisplayViewController"];
    PPTopic *topic = [self.topicArray objectAtIndex:image.tag];
    targetVC.topic = topic;
    [self.addCommentTF resignFirstResponder];
    self.commentView.hidden = YES;
    [self.navigationController pushViewController:targetVC animated:YES];
}


- (void)pressRock:(UIButton *)sender
{
    PPTopic *topic = [self.topicArray objectAtIndex:sender.tag];
    NSString *url = [PPAPIList getAPIList].PPAddTopicLike;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"topicId":@(topic.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObject[@"errorMsg"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        
        //replace
        NSString *queryUrl = [PPAPIList getAPIList].PPQueryTopicById;
        NSDictionary *queryParams = @{@"topicId":@(topic.id)};
        [httpRequst POST:queryUrl parameters:queryParams success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"topic Json is %@",responseObject);
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicArray = resultMap[@"topic"];
            NSError *err = nil;
            PPTopic *replaceTopic = [[PPTopic alloc] initWithDictionary:topicArray.firstObject error:&err];
            [self.topicArray replaceObjectAtIndex:sender.tag withObject:replaceTopic];
            [self.myTableView reloadData];
        }failure:^(AFHTTPRequestOperation *operation , NSError *error){
            
        }];

        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        
    }];
}

- (void)pressComment:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
    [self.myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    PPPetCircleTableViewCell *cell = (PPPetCircleTableViewCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
    self.commentView.hidden = NO;
    [self.addCommentTF becomeFirstResponder];
    CGPoint point = CGPointMake(0, cell.frame.size.height + self.keyboardHeight + 44 - self.view.frame.size.height + [self getBeforCellHeight:sender.tag]/*sender.tag * cell.frame.size.height*/);
    [self.myTableView setContentOffset:point animated:YES];
    self.addCommentTF.tag = sender.tag;
    self.targetId = 0;
}

- (void)pushToUserCenter:(UIButton *)sender
{
    PPTopic *topic = [self.topicArray objectAtIndex:sender.tag];
    if (topic.userId == [PPSystemConfiguraton sharedSystemConfiguration].userInfo.id) {
        //myCenter
        PPUserCenterMainPageTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPUserCenterMainPageTableViewController"];
        [self.navigationController pushViewController:targetVC animated:YES];
    }else{
        PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
        targetVC.user = topic.userList.firstObject;
        [self.navigationController pushViewController:targetVC animated:YES];

    }
}

- (IBAction)backButton:(id)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

//pub
- (IBAction)pubCommentButton:(id)sender {
    if (!self.addCommentTF.text.length > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发布内容不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    [HUD showUIBlockingIndicatorWithText:@"正在处理"];
    PPTopic *topic = [self.topicArray objectAtIndex:self.addCommentTF.tag];
    NSString *url = [PPAPIList getAPIList].PPAddOrReplyComment;
    NSDictionary *params =@{@"content":self.addCommentTF.text,@"topicId":@(topic.id),@"userId":@(self.config.userInfo.id),@"targetUserId":@(self.targetId)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        [HUD hideUIBlockingIndicator];
        NSLog(@"public reply json is %@",responseObject);
        [self.addCommentTF resignFirstResponder];
        self.commentView.hidden = YES;
        self.addCommentTF.text = @"";
        //replace
        NSString *queryUrl = [PPAPIList getAPIList].PPQueryTopicById;
        NSDictionary *queryParams = @{@"topicId":@(topic.id)};
        [httpRequst POST:queryUrl parameters:queryParams success:^(AFHTTPRequestOperation *operation, id responseObject){
            NSLog(@"topic Json is %@",responseObject);
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicArray = resultMap[@"topic"];
            NSError *err = nil;
            PPTopic *replaceTopic = [[PPTopic alloc] initWithDictionary:topicArray.firstObject error:&err];
            [self.topicArray replaceObjectAtIndex:self.addCommentTF.tag withObject:replaceTopic];
            [self.myTableView reloadData];
        }failure:^(AFHTTPRequestOperation *operation , NSError *error){
            
        }];

        
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        
    }];
    
    
}

- (IBAction)goPub:(id)sender {
    PPSelectTagViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPSelectTagViewController"];
    [self.navigationController pushViewController:targetVC animated:YES];
}


#pragma mark - Text Field
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.commentView.hidden = YES;
    return YES;
}
#pragma mark - ScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(self.canLoadMore)
    {
        [refreshView egoRefreshScrollViewDidScroll:scrollView];
    }
    
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.canReturn) {
        [self.addCommentTF resignFirstResponder];
        self.commentView.hidden = YES;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
